import { useState, useRef, useEffect, createContext, useContext, useCallback } from 'react'
import { ConnContext } from './Conn'

/**
 * BookContext & BookProvider
 * 
 * "Book" is the collection of tables fetched from backend. The BookContext
 * provides the functionality of fetching specific table from backend and 
 * caches it in the frontend, so that to avoid accessing backend each time
 * when opening a page/form/table.
 * 
 */

const BookContext = createContext({
  fetchTable: () => {},
  storeTable: () => {},
})

const newBook = (origBook, bookKey, data) => {
  return {...origBook, [bookKey]: data};
}

const BookProvider = ({children}) => {

  const {send, cast} = useContext(ConnContext);

  const [book, setBook] = useState({});

  const [prog, setProg] = useState();

  const updateBook = useCallback(({name, data}) => {
    console.log('book updated', name, data);
    setBook(newBook(book, name, data));
  }, [book]);
  
  const fetchTable = ({name, cond}) => {
    cast('table', updateBook);
    send('table', {name, cond});
  }

  const storeTable = (table, records) => {
    cast(`${table}-store`, setProg);
    send(`${table}-store`, records);
  } 

  const provided = {
    book,
    storeTable,
    fetchTable
  }

  return <BookContext.Provider value={provided}>
    {children}
  </BookContext.Provider>
}

export {
  BookContext,
  BookProvider,
}